import React, { useReducer } from 'react'

const initialState = [{ id: 1, name: 'kaho' }]

const reducer = (state: any, { type, payload }: any) => {
    switch (type) {
        case 'add':
            return [...state, payload]

        case 'remove':
            return state.filter((item: any) => item.id !== payload.id)

        case 'clear':
            return []

        default:
            return state
    }
}

const ReducerText = () => {
    const [state, dispatch] = useReducer(reducer, initialState)

    return (
        <div>
            <button onClick={() => {dispatch({type: 'add', payload: {id: 2, name: 'zxc'}})}}>新增</button>
            <button onClick={() => {dispatch({type: 'remove', payload: {id: 1}})}}>移除</button>
            <button onClick={() => {dispatch({type: 'clear'})}}>清除</button>
            {state.map((item: any) => <p key={item.id}>
                {item.name}
            </p>)}
            
        </div>
    )
}

export default ReducerText
